<?php
/**
 * 公共控制器
 * @version 1.0
 * @author: HuangYu <992287102@qq.com>
 * @since: 2019/4/2 15:30
 * Class CommonController
 * @package app\index\controller\demo
 */

namespace app\index\controller\demo;

use app\index\controller\BaseController;

class CommonController extends BaseController
{
    //用户信息
    protected $user;
    //用户id
    protected $userId;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();

        //初始化全局变量
        $this->initData();
    }

    /**
     * 初始化全局变量
     * @return bool
     */
    private function initData()
    {
        //token用户信息
        $this->user   = $this->getTokenInfo();
        $this->userId = $this->user['id'];

        return true;
    }

    /**
     * 获取token用户信息
     * @author: HuangYu
     * @date: 2019/1/16
     * @return array
     */
    private function getTokenInfo()
    {
        //获取token
        $token     = $this->request->header('Authorization');
        $tokenUser = [];
        if ($token) {
            $token     = trim(substr($token, 6));
            $tokenUser = cache($token);
            if (!$tokenUser) {
                //通过token获取用户信息（接口）
                $url  = 'http://platform-service/';
                $data = curlRequest($url . 'auth/checkAccessToken?accessToken=' . $token);
                if ($data && isset($data['code']) && $data['code'] == '000') {
                    //缓存用户信息
                    $tokenUser = $data['data']['userInfo'];
                    cache($token, $tokenUser, 7200);
                }
            }
        }
        if (!$tokenUser) {
            $tokenUser = [
                'id'       => 0,
                'nickname' => '',
                'code'     => '',
                'avatar'   => ''
            ];
        }

        return $tokenUser;
    }
}